package com.senseauto.camera2record;

import android.content.Context;
import android.content.res.Configuration;
import android.graphics.ImageFormat;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.SurfaceTexture;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCaptureSession;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraDevice;
import android.hardware.camera2.CameraManager;
import android.hardware.camera2.CameraMetadata;
import android.hardware.camera2.CaptureFailure;
import android.hardware.camera2.CaptureRequest;
import android.hardware.camera2.CaptureResult;
import android.hardware.camera2.TotalCaptureResult;
import android.hardware.camera2.params.StreamConfigurationMap;
import android.media.Image;
import android.media.ImageReader;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.util.Size;
import android.util.SparseIntArray;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;


import com.senseauto.camera2record.utils.AutoFitTextureView;
import com.senseauto.camera2record.utils.PhotoUtil;
import com.senseauto.camera2record.utils.TimeUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * 预览摄像头，拍照
 * 录视频（车机上MediaCodec硬编码录视频底部有绿条，平板和手机上不会，车机上MediaRecorder录制视频不会，尝试用FFmpeg手动编码录制视频(和MediaCodec类似)）
 */

public class Camera2Activity extends AppCompatActivity implements View.OnClickListener {
    private static final int SENSOR_ORIENTATION_DEFAULT_DEGREES = 90;
    private static final int SENSOR_ORIENTATION_INVERSE_DEGREES = 270;
    private static final SparseIntArray DEFAULT_ORIENTATIONS = new SparseIntArray();
    private static final SparseIntArray INVERSE_ORIENTATIONS = new SparseIntArray();
    private static final SparseIntArray INVERSE_ORIENTATIONS2 = new SparseIntArray();
    private boolean showImageSize = false;
    private static final String TAG = "Camera2Activity";

    static {
        DEFAULT_ORIENTATIONS.append(Surface.ROTATION_0, 90);
        DEFAULT_ORIENTATIONS.append(Surface.ROTATION_90, 0);
        DEFAULT_ORIENTATIONS.append(Surface.ROTATION_180, 270);
        DEFAULT_ORIENTATIONS.append(Surface.ROTATION_270, 180);
    }

    static {
        INVERSE_ORIENTATIONS.append(Surface.ROTATION_0, 270);
        INVERSE_ORIENTATIONS.append(Surface.ROTATION_90, 180);
        INVERSE_ORIENTATIONS.append(Surface.ROTATION_180, 90);
        INVERSE_ORIENTATIONS.append(Surface.ROTATION_270, 0);
    }

    private AutoFitTextureView mTextureView;
    private TextView timeTv;
    private Button  mBtnRecord;
    private CameraDevice mCameraDevice;
    private int cameraId;
    private CameraCaptureSession.CaptureCallback mSessionCaptureCallback;
    private int previewWidth, previewHeight;
    private CameraCaptureSession mPreviewSession;
    public static int MSG_ID_UPDATE_TIME = 99;
    private int recordTime;//录制了多少秒

    private Size mPreviewSize;
    private boolean mIsRecordingVideo;
    private HandlerThread mBackgroundThread;
    private Handler mBackgroundHandler;
    private ImageReader mImageReader;
    private Semaphore mCameraOpenCloseLock = new Semaphore(1);
    private boolean takePhotoFlag = true;
    private Integer mSensorOrientation;
    private VideoEnCodec videoEnCodec;
    private long frameIndex = 0;
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
    private CameraDevice.StateCallback mStateCallback = new CameraDevice.StateCallback() {

        @Override
        public void onOpened(@NonNull CameraDevice cameraDevice) {
            Log.e(TAG, "mStateCallback onOpened: ");
            mCameraDevice = cameraDevice;
            startPreview();
            mCameraOpenCloseLock.release();
            if (null != mTextureView) {
                configureTransform(mTextureView.getWidth(), mTextureView.getHeight());
            }
            createCameraPreviewSession();
        }

        @Override
        public void onDisconnected(@NonNull CameraDevice cameraDevice) {
            Log.e(TAG, "mStateCallback onDisconnected: ");
            mCameraOpenCloseLock.release();
            cameraDevice.close();
            mCameraDevice = null;
        }

        @Override
        public void onError(@NonNull CameraDevice cameraDevice, int error) {
            Log.e(TAG, "mStateCallback onError: "+error);
            mCameraOpenCloseLock.release();
            cameraDevice.close();
            mCameraDevice = null;
//            finish();
        }

    };
    private String mNextVideoAbsolutePath;
    private CaptureRequest.Builder mPreviewBuilder;

    private static Size chooseVideoSize(Size[] choices) {
        for (Size size : choices) {
            if (size.getWidth() == size.getHeight() * 4 / 3 && size.getWidth() <= 1080) {
                return size;
            }
        }
        Log.e(TAG, "Couldn't find any suitable video size");
        return choices[choices.length - 1];
    }

    private static Size chooseOptimalSize(Size[] choices, int width, int height, Size aspectRatio) {
        // Collect the supported resolutions that are at least as big as the preview Surface
        List<Size> bigEnough = new ArrayList<>();
        int w = aspectRatio.getWidth();
        int h = aspectRatio.getHeight();
        for (Size option : choices) {
            if (option.getHeight() == option.getWidth() * h / w &&
                    option.getWidth() >= width && option.getHeight() >= height) {
                bigEnough.add(option);
            }
        }
        if (bigEnough.size() > 0) {
            return Collections.min(bigEnough, new CompareSizesByArea());
        } else {
            Log.e(TAG, "Couldn't find any suitable preview size");
            return choices[0];
        }
    }

    //更新显示录制的时间
    Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == MSG_ID_UPDATE_TIME) {
                recordTime++;
                updateTime();
                handler.sendEmptyMessageDelayed(MSG_ID_UPDATE_TIME, 1000);
            }
        }
    };

    public void updateTime() {
        String time = TimeUtil.sumSecondToTime(recordTime);
        timeTv.setText(time);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.e(TAG, "---onCreate");
        setContentView(R.layout.activity_camera2);
        if (getIntent() != null) {
            cameraId = Integer.parseInt(getIntent().getStringExtra("dmsCameraID"));
            previewWidth = getIntent().getIntExtra("width", 1920);
            previewHeight = getIntent().getIntExtra("height", 1080);
        }
        timeTv = findViewById(R.id.tvTime);
        mTextureView = (AutoFitTextureView) findViewById(R.id.texture);

        findViewById(R.id.takePhoto).setOnClickListener(this);
        mBtnRecord = findViewById(R.id.btnRecordVideo);
        mBtnRecord.setOnClickListener(this);
        videoEnCodec = new VideoEnCodec();
        String fileName = sdf.format(new Date())+".mp4";
        String filePath = new File(getExternalCacheDir(), fileName).getAbsolutePath();
        Log.e(TAG, "filePath="+filePath);
        videoEnCodec.initEnCodec(filePath, previewWidth, previewHeight);

        initSessionCaptureCallback();
        mTextureView.setSurfaceTextureListener(new TextureView.SurfaceTextureListener() {
            @Override
            public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
                //可以使用surface,在这里打开摄像头
                openCamera(mTextureView.getWidth(), mTextureView.getHeight());
            }

            @Override
            public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
                //纹理尺寸变化

            }

            @Override
            public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {

                return false;
            }

            @Override
            public void onSurfaceTextureUpdated(SurfaceTexture surface) {


            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        startBackgroundThread();
        //不要在onResume里openCamera，而是在textureView的onSurfaceTextureAvailable打开摄像头，不然重新进入录屏界面会报错说session关闭了
    }

    @Override
    public void onPause() {
        closeCamera();
        if (mBackgroundThread != null) {
            stopBackgroundThread();
        }
        handler.removeMessages(MSG_ID_UPDATE_TIME);
        super.onPause();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bt_back: {
                closeCamera();
                if (mBackgroundThread != null) {
                    stopBackgroundThread();
                }
                finish();
            }
            break;
            case R.id.btnRecordVideo: {
                if(!mIsRecordingVideo){
                    mIsRecordingVideo = true;
                    mBtnRecord.setText("录制中");
                }else{
                    mIsRecordingVideo = false;
                    mBtnRecord.setText("录制");
                    videoEnCodec.endClose();
                }


                break;
            }
            case R.id.takePhoto:{
                takePhotoFlag = false;
            }
        }
    }


    private void startBackgroundThread() {
        mBackgroundThread = new HandlerThread("CameraBackground");
        mBackgroundThread.start();
        mBackgroundHandler = new Handler(mBackgroundThread.getLooper());
    }

    private void stopBackgroundThread() {
        mBackgroundThread.quitSafely();
        try {
            mBackgroundThread.join();
            mBackgroundThread = null;
            mBackgroundHandler = null;
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @SuppressWarnings("MissingPermission")
    private void openCamera(int width, int height) {
        Log.e(TAG, "openCamera: " + width + "---" + height);
        setUpCameraOutputs(width, height);

        CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
        try {
            Log.e(TAG, "tryAcquire");
            if (!mCameraOpenCloseLock.tryAcquire(2500, TimeUnit.MILLISECONDS)) {
                throw new RuntimeException("Time out waiting to lock camera opening.");
            }

            CameraCharacteristics characteristics = manager.getCameraCharacteristics(String.valueOf(cameraId));
            StreamConfigurationMap map = characteristics
                    .get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
            mSensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
            if (map == null) {
                throw new RuntimeException("Cannot get available preview/video sizes");
            }

            if (previewHeight > 0 && previewWidth > 0) {
                mPreviewSize = new Size(previewWidth, previewHeight);

            } else {
                mPreviewSize = new Size(1920, 1080);
            }

            Log.e(TAG, "openCamera: " + mPreviewSize.getWidth() + "---" + mPreviewSize.getHeight());

            int orientation = getResources().getConfiguration().orientation;
            if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
                mTextureView.setAspectRatio(mPreviewSize.getWidth(), mPreviewSize.getHeight());
            } else {
                mTextureView.setAspectRatio(mPreviewSize.getHeight(), mPreviewSize.getWidth());
            }
            configureTransform(width, height);
            manager.openCamera(String.valueOf(cameraId), mStateCallback, null);
        } catch (CameraAccessException e) {
            Toast.makeText(this, "Cannot access the camera.", Toast.LENGTH_SHORT).show();
            finish();
        } catch (NullPointerException e) {
            e.printStackTrace();
            Toast.makeText(this, "摄像头打开失败", Toast.LENGTH_SHORT).show();
        } catch (InterruptedException e) {
            throw new RuntimeException("Interrupted while trying to lock camera opening.");
        }
    }

    @SuppressWarnings("SuspiciousNameCombination")
    private void setUpCameraOutputs(int width, int height) {
        mImageReader = ImageReader.newInstance(previewWidth, previewHeight,  ImageFormat.YUV_420_888, 2);
        Log.e(TAG, "previewWidth=" + previewWidth + " previewHeight=" + previewHeight);
        mImageReader.setOnImageAvailableListener( mOnImageAvailableListener, mBackgroundHandler);
    }


    private final ImageReader.OnImageAvailableListener mOnImageAvailableListener
            = new ImageReader.OnImageAvailableListener() {

        @Override
        public void onImageAvailable(ImageReader reader) {

            Image image = reader.acquireLatestImage();
            if (image == null) {
                return;
            }
            if(!showImageSize){
                Log.e(TAG, "image.width="+image.getWidth()+" image.Height="+image.getHeight()+" previewWidth ="+previewWidth +"  previewHeight="+ previewHeight);
                showImageSize = true;
            }
            ByteBuffer bufferY = image.getPlanes()[0].getBuffer();
            byte[] dataY = new byte[bufferY.remaining()];
            bufferY.get(dataY);

            ByteBuffer bufferUV = image.getPlanes()[2].getBuffer();
            byte[] dataUV = new byte[bufferUV.remaining()];
            bufferUV.get(dataUV);

            image.close();


            long timer = System.currentTimeMillis();
            mCount++;
            if (mIsFirstCount) {
                mCurrentTime = timer;
                mIsFirstCount = false;
            } else {
                int cost = (int) (timer - mCurrentTime);
                if (cost >= 1000) {
                    mCurrentTime = timer;
                    mFps = (((float) mCount * 1000) / cost);
                    mCount = 0;
                }
            }
            Log.d(TAG, "onImageAvailable: test lakin 55555 FPS: " + mFps);

            if (mImageData == null || mImageData.length != previewWidth * previewHeight * 3 / 2) {
                long size = previewWidth * previewHeight * 3 / 2;
                Log.e(TAG, "size="+size);
                if(mImageData != null){
                    Log.e(TAG, "mImageData.length  ==》"+mImageData.length );
                }
                mImageData = new byte[previewWidth * previewHeight * 3 / 2];
            }
            synchronized (mImageDataLock) {
                System.arraycopy(dataY, 0, mImageData, 0, dataY.length);
                System.arraycopy(dataUV, 0, mImageData, previewWidth * previewHeight, dataUV.length);
            }

            if (!takePhotoFlag) {
                Log.e(TAG, "mImageData.length="+mImageData.length);
                //保存yuv数据到本地，7yuv可打开查看yuv图片数据
                PhotoUtil.createFileWithByte(Camera2Activity.this, mImageData, 0);
                takePhotoFlag = true;
            }
            if(mIsRecordingVideo){//录制视频
                videoEnCodec.pushFrame(frameIndex, mImageData );
                frameIndex++;
            }else{
                frameIndex = 0;
            }
        }

    };

    public static void yuv2Picture(byte[] data, int width, int height, File targetFile) {
        FileOutputStream stream = null;
        try {
            android.graphics.YuvImage image = new android.graphics.YuvImage(data, ImageFormat.NV21, width, height, null);
            stream = new FileOutputStream(targetFile);
            if (image.compressToJpeg(new Rect(0, 0, width, height), 100, stream)) {
                stream.flush();
            }
        } catch (Exception e) {
            Log.e(TAG, e.toString(), e);
        } finally {
            if (stream != null) {
                try {
                    stream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    protected byte[] mImageData;
    private Object mImageDataLock = new Object();

    private boolean hah = false;
    private boolean isone = true;
    private int frame;


    private Handler mHandler = new Handler();
    //for test fps
    protected float mFps;
    protected int mCount = 0;
    protected long mCurrentTime = 0;
    protected boolean mIsFirstCount = true;
    protected int haha2;

    private void closeCamera() {
        try {
            mCameraOpenCloseLock.acquire();
            closePreviewSession();
            if (null != mCameraDevice) {
                mCameraDevice.close();
                mCameraDevice = null;
            }

        } catch (InterruptedException e) {
            throw new RuntimeException("Interrupted while trying to lock camera closing.");
        } finally {
            mCameraOpenCloseLock.release();
        }
    }


    private void startPreview() {
        if (null == mCameraDevice || !mTextureView.isAvailable() || null == mPreviewSize) {
            return;
        }
        try {
            //Log.e(TAG, "startPreview()-->下面有closePreviewSession()");
            //closePreviewSession();//这里注释了！！！不然会出现updatePreview(Camera2Activity.java:743)里报错IllegalStateException: Session has been closed; further changes are illegal.
            SurfaceTexture texture = mTextureView.getSurfaceTexture();
            assert texture != null;
            texture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());
            mPreviewBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);

            Surface previewSurface = new Surface(texture);
            mPreviewBuilder.addTarget(previewSurface);

            mCameraDevice.createCaptureSession(Collections.singletonList(previewSurface),
                    new CameraCaptureSession.StateCallback() {

                        @Override
                        public void onConfigured(@NonNull CameraCaptureSession session) {
                            mPreviewSession = session;
                            Log.e(TAG, "startPreview()-->mCameraDevice.createCaptureSession-->onConfigured");

                            updatePreview(session);
                        }

                        @Override
                        public void onConfigureFailed(@NonNull CameraCaptureSession session) {
                            Toast.makeText(Camera2Activity.this, "Failed", Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onClosed(@NonNull CameraCaptureSession session) {
                            super.onClosed(session);
                            Log.e(TAG, "startPreview()-->mCameraDevice.createCaptureSession-->onClosed");
                        }
                    }, mBackgroundHandler);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }


    private void updatePreview(CameraCaptureSession session) {
        if (null == mCameraDevice) {
            return;
        }
        try {
            setUpCaptureRequestBuilder(mPreviewBuilder);
            session.setRepeatingRequest(mPreviewBuilder.build(), null, mBackgroundHandler);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }

    private void setUpCaptureRequestBuilder(CaptureRequest.Builder builder) {
        builder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);
    }


    private CaptureRequest.Builder mPreviewRequestBuilder;

    private CameraCaptureSession mCaptureSession;

    private CaptureRequest mPreviewRequest;

    private void createCameraPreviewSession() {
        try {
            SurfaceTexture texture = mTextureView.getSurfaceTexture();
            assert texture != null;

            texture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());
            Surface surface = new Surface(texture);
            mPreviewRequestBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
            mPreviewRequestBuilder.addTarget(mImageReader.getSurface());
            mPreviewRequestBuilder.addTarget(surface);

            mCameraDevice.createCaptureSession(Arrays.asList(surface, mImageReader.getSurface()),
                    new CameraCaptureSession.StateCallback() {

                        @Override
                        public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession) {
                            if (null == mCameraDevice) {
                                return;
                            }
                            mCaptureSession = cameraCaptureSession;
                            try {
                                mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE,
                                        CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);

                                mPreviewRequest = mPreviewRequestBuilder.build();
                                mCaptureSession.setRepeatingRequest(mPreviewRequest,
                                        null, mBackgroundHandler);
                            } catch (CameraAccessException e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onConfigureFailed(
                                @NonNull CameraCaptureSession cameraCaptureSession) {

                        }
                    }, null
            );
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }

    private void configureTransform(int viewWidth, int viewHeight) {
        if (null == mTextureView || null == mPreviewSize) {
            return;
        }
        int rotation = getWindowManager().getDefaultDisplay().getRotation();
        Matrix matrix = new Matrix();
        RectF viewRect = new RectF(0, 0, viewWidth, viewHeight);
        RectF bufferRect = new RectF(0, 0, mPreviewSize.getHeight(), mPreviewSize.getWidth());
        float centerX = viewRect.centerX();
        float centerY = viewRect.centerY();
        if (Surface.ROTATION_90 == rotation || Surface.ROTATION_270 == rotation) {
            bufferRect.offset(centerX - bufferRect.centerX(), centerY - bufferRect.centerY());
            matrix.setRectToRect(viewRect, bufferRect, Matrix.ScaleToFit.FILL);
            float scale = Math.max(
                    (float) viewHeight / mPreviewSize.getHeight(),
                    (float) viewWidth / mPreviewSize.getWidth());
            matrix.postScale(scale, scale, centerX, centerY);
            matrix.postRotate(90 * (rotation - 2), centerX, centerY);
        }
        mTextureView.setTransform(matrix);
    }


    private void closePreviewSession() {
        if (mPreviewSession != null) {
            Log.e(TAG, "closePreviewSession()");
            mPreviewSession.close();
            mPreviewSession = null;
        }
    }


    static class CompareSizesByArea implements Comparator<Size> {

        @Override
        public int compare(Size lhs, Size rhs) {
            return Long.signum((long) lhs.getWidth() * lhs.getHeight() -
                    (long) rhs.getWidth() * rhs.getHeight());
        }

    }

    private void initSessionCaptureCallback() {
        mSessionCaptureCallback = new CameraCaptureSession.CaptureCallback() {
            @Override
            public void onCaptureStarted(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, long timestamp, long frameNumber) {
                super.onCaptureStarted(session, request, timestamp, frameNumber);
            }

            @Override
            public void onCaptureProgressed(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, @NonNull CaptureResult partialResult) {
                super.onCaptureProgressed(session, request, partialResult);
            }

            @Override
            public void onCaptureCompleted(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, @NonNull TotalCaptureResult result) {
                super.onCaptureCompleted(session, request, result);
            }

            @Override
            public void onCaptureFailed(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, @NonNull CaptureFailure failure) {
                super.onCaptureFailed(session, request, failure);
            }
        };
    }
}

